package com.sdruixinggroup.mondayb2b.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.Ucenter;
import com.sdruixinggroup.mondayb2b.ui.Activities.AddressActivity;
import com.sdruixinggroup.mondayb2b.ui.Activities.MineCollectActivity;
import com.sdruixinggroup.mondayb2b.utils.UserInfoUtil;
import com.sdruixinggroup.mondayb2b.widget.GlideCircleTransform;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import www.library.PullToRefreshBase;
import www.library.PullToRefreshScrollView;

import static com.sdruixinggroup.mondayb2b.utils.DisplayUtil.double2String;
import static com.sdruixinggroup.mondayb2b.utils.UserInfoUtil.TOKEN_OUT_TIME;
import static com.sdruixinggroup.mondayb2b.utils.UserInfoUtil.TOKEN_OUT_TIME_ERROR;

/**
 * Created by tangjie on 2017/11/9.
 */

public class MineActivity extends BaseActivity implements View.OnClickListener, MainActivity.OnTabActivityResultListener{
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_count)
    TextView tvMessageCount;
    @BindView(R.id.my_address)
    LinearLayout myAddress;
    @BindView(R.id.my_money)
    TextView myMoney;
    @BindView(R.id.tv_balance)
    TextView tvBalance;
    @BindView(R.id.tv_coupon)
    TextView tvCoupon;
    @BindView(R.id.tv_commission)
    TextView tvCommission;
    @BindView(R.id.tv_loan)
    TextView tvLoan;
    @BindView(R.id.ll_pay)
    LinearLayout llPay;
    @BindView(R.id.ll_send)
    LinearLayout llSend;
    @BindView(R.id.ll_delivery)
    LinearLayout llDelivery;
    @BindView(R.id.ll_appraise)
    LinearLayout llAppraise;
    @BindView(R.id.ll_verify)
    LinearLayout llVerify;
    @BindView(R.id.scrollView)
    PullToRefreshScrollView scrollView;
    private ImageView my_protrait;
    private ImageView my_setting;
    private LinearLayout my_leftmoney, my_voucher, my_earnings, my_loan;
    private Intent webintent;
    private LinearLayout my_question, my_prizes, my_collect, my_address, my_share, my_phone;
    private RelativeLayout my_message;


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Object resp) {/* Do something */
        if (resp instanceof Integer) {
            Integer integer = (Integer) resp;
            Log.e("HQQ", "onMessageEvent ");
            if (integer == 123) {
                queryCenter();
            } else if (integer == 124) {
                tvName.setText("");
                tvMessageCount.setVisibility(View.GONE);
                tvBalance.setText(String.valueOf(0));
                tvCoupon.setText(String.valueOf(0));
                tvCommission.setText(String.valueOf(0));
                tvLoan.setText(String.valueOf(0));
                my_protrait.setBackgroundResource(R.drawable.my_portrait);
            }
        }

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        webintent = new Intent(this, WebActivity.class);
        initview();
        queryCenter();
    }

    private void initview() {
        my_prizes = (LinearLayout) findViewById(R.id.my_prizes);
        my_prizes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toWebView("lotterylist?");
            }
        });
        my_protrait = (ImageView) findViewById(R.id.my_protrait);
        my_protrait.setOnClickListener(this);

        my_setting = (ImageView) findViewById(R.id.my_setting);
        my_setting.setOnClickListener(this);

        my_leftmoney = (LinearLayout) findViewById(R.id.my_leftmoney);
        my_leftmoney.setOnClickListener(this);

        my_voucher = (LinearLayout) findViewById(R.id.my_voucher); //我的代金券
        my_voucher.setOnClickListener(this);

        my_earnings = (LinearLayout) findViewById(R.id.my_earnings);
        my_earnings.setOnClickListener(this);

        my_loan = (LinearLayout) findViewById(R.id.my_loan);
        my_loan.setOnClickListener(this);

        my_collect = (LinearLayout) findViewById(R.id.my_collect);
        my_collect.setOnClickListener(this);
        tvName.setOnClickListener(this);
        findViewById(R.id.my_question).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                webintent.putExtra(WebActivity.INTENT_EXTRA_BEGIN_URL, "http://demo.chenc.site/#/address");
                getParent().startActivity(webintent);
            }
        });
        findViewById(R.id.my_share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toWebView("share?");
            }
        });
        findViewById(R.id.my_phone).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                toWebView("service?");
            }
        });
        findViewById(R.id.my_question).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toWebView("myask?");
            }
        });

        findViewById(R.id.my_order_detail).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MineActivity.this, MyOrderActivity.class));
            }
        });

        my_message = (RelativeLayout) findViewById(R.id.my_message);
        my_message.setOnClickListener(this);

        scrollView.getRefreshableView().fling(600);
        scrollView.getRefreshableView().setSmoothScrollingEnabled(true);
        scrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2(){
            @Override
            public void onPullDownToRefresh(PullToRefreshBase refreshView) {
                queryCenter();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase refreshView) {


            }
        });
    }

    @Override
    public void onClick(View view) {
        if (view == my_protrait || view == tvName) {
            startActivity(new Intent(this, MineDetailActivity.class));
        }
        if (view == my_setting) {
            startActivity(new Intent(this, SettingActivity.class));
        }

        if (view == my_leftmoney) {
            toWebView("mypocket?");
        }
        if (view == my_loan) {
            toWebView("loanslist?");
        }
        if (view == my_voucher) {
            toWebView("coupon?");
        }
        if (view == my_earnings) {
            toWebView("benefitdetail?");
        }

        if (view == my_collect) {
            Intent intent = new Intent(getBaseContext(), MineCollectActivity.class);
            startActivity(intent);
        }

        if (view == my_message) {
            Intent intent = new Intent(getBaseContext(), MessageNoticeActivity.class);
            startActivity(intent);
        }

    }


    private void queryCenter() {
        String url = API.UCENTER + UserInfoUtil.getInfoToken(getApplicationContext());
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");
        TypeToken<Ucenter> typeToken = new TypeToken<Ucenter>() {
        };
        OkHttpUtils.get().url(url).headers(heades).build().execute(new ObjectCallBack<Ucenter>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {
                if(null != scrollView){
                    scrollView.onRefreshComplete();
                }
            }

            @Override
            public void onResponse(Ucenter response, int id) {

                try {
                    if (null != response) {
                        if (response.getErr_code() == 0) {
                            Ucenter.MemberBean bean = response.getMember();
                            tvName.setText(bean.getNickname());
                            int message_count = response.getMessage_count();
                            if (message_count == 0) {
                                tvMessageCount.setVisibility(View.GONE);
                            } else {
                                tvMessageCount.setVisibility(View.VISIBLE);
                                tvMessageCount.setText(String.valueOf(response.getMessage_count()));
                            }
                            tvBalance.setText(double2String(response.getMember().getBalance()));
                            tvCoupon.setText(String.valueOf(response.getCoupon_count()));
                            tvCommission.setText(double2String(response.getTotal_commission()));
                            tvLoan.setText(double2String(response.getTotal_loan()));
                            Glide.with(MineActivity.this).load(bean.getAvatar()).transform(new GlideCircleTransform(MineActivity.this)).error(R.drawable.my_portrait).into(my_protrait);
                        } else if (response.getErr_code() == TOKEN_OUT_TIME || response.getErr_code() == TOKEN_OUT_TIME_ERROR) {
                            UserInfoUtil.intoLogin(MineActivity.this);
                        } else {
                            showToast(response.getErr_msg());
                        }
                    }
                } catch (Throwable throwable) {

                }
                if(null != scrollView){
                    scrollView.onRefreshComplete();
                }
            }


        });

    }

    @OnClick(R.id.my_address)
    public void onClick() {
        Intent intent = new Intent(this, AddressActivity.class);
        startActivity(intent);
    }

    @OnClick({R.id.ll_pay, R.id.ll_send, R.id.ll_delivery, R.id.ll_appraise, R.id.ll_verify})
    public void onClickLL(View view) {
        Intent intent = new Intent(getBaseContext(), MyOrderActivity.class);
        switch (view.getId()) {
            case R.id.ll_pay:
                intent.putExtra("index", 1);
                break;
            case R.id.ll_send:
                intent.putExtra("index", 2);
                break;
            case R.id.ll_delivery:
                intent.putExtra("index", 3);
                break;
            case R.id.ll_appraise:
                intent.putExtra("index", 4);
                break;
            case R.id.ll_verify:
                intent.putExtra("index", 5);
                break;
        }

        //startActivity(intent);
        if(getParent()!= null){
            getParent().startActivityForResult(intent,12345);
        }else {
            startActivity(intent);
        }

    }

    private void toWebView(String param) {
        Intent intent = new Intent(getBaseContext(), WebActivity.class);
        intent.putExtra(WebActivity.INTENT_EXTRA_BEGIN_URL, param);

        if(getParent()!= null){
            getParent().startActivityForResult(intent,12345);
        }else {
            startActivity(intent);
        }
    }

    @OnClick(R.id.ll_verify)
    public void onViewClicked() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 12345:
                queryCenter();
                break;
        }
    }

    @Override
    public void onTabActivityResult(int requestCode, int resultCode, Intent data) {
        onActivityResult(requestCode,resultCode,data);
    }

    @Override
    public void onBackPressed() {
        finish();
    }
}
